package com.itheima.thread.communication.demo05;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

// 生产者线程的任务类
public class ProducerThread implements Runnable {

    private Box box  ;
    private ReentrantLock reentrantLock ;
    private Condition condition ;
    public ProducerThread(Box box , ReentrantLock reentrantLock , Condition condition) {        // 定义接收奶箱的构造方法
        this.box = box ;
        this.reentrantLock = reentrantLock ;
        this.condition = condition ;
    }

    // 定义一个标志位的变量
    private int count = 0 ;

    @Override
    public void run() {

        // 创建Box对象
        // Box box = new Box() ;

        while(true) {

            // 加锁
            reentrantLock.lock();

            // 判断奶箱中是否有奶，如果有奶，进行等待
            if(box.isFlag()) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            if(count % 2 == 0) {

                box.setMilkType("牛奶");
                box.setAmount("5L");

            }else {

                box.setMilkType("羊奶");
                box.setAmount("10L");

            }

            // 更改flag的值为true
            box.setFlag(true);

            // 唤醒消费者线程，进行消费
            condition.signal();

            // 释放锁
            reentrantLock.unlock();

            // 对标志位的变量进行++操作
            count++;

        }

    }

}
